nie.define("Index",function(){

    'use strict';
    var Base = nie.require('Base'),
        API = nie.require('API');
    var CONSTANT = ['A','B','C'];
    
     Base.init();
     Object.size = function(obj) {
        var size = 0, key;
        for (key in obj) {
            if (obj.hasOwnProperty(key)) size++;
        }
        return size;
    };
    Vue.use(VueAwesomeSwiper);
     const App = new Vue({
        el:"#app",
        data:{
            isHome: false,
            sPop: false,
            sPopAttention: false,
            sPopDt: false,
            finishUsers:0,
            sPopJlsm: false,
            sPopDt: false,
            sPopTo: false,
            sPopHdgz: false,
            sPopProfile: false,
            sPopFdjh: false,
            sPopLqtz: false,
            sPopDtjs: false,
            sPopFdpd: false,
            valChance: true,
            codeTxt:'获取验证码',
            score: 0,
            sendCodeed: false,
            sendTime: 60,
            mobile: '',
            mobileCode: '',
            logined: false,
            loginId: '',
            loginToken: '',
            questionList: [],
            countDown: 10,
            questionIndex: 0,
            jltxt:'',
            university:'',
            answerList:[],
            dtresult:'',
            nextText:'下一题',
            gfTxt: '',
            rank:'',
            sLightPop: false,
            prizeRecord:{
                '4':{count:0},
                '1':{count:0},
                '2':{count:0},
                '3':{count:0},
                '7':{count:0},
                '6':{count:0},
                '5':{count:0}
            },
            fxfdText: '分享获复读',
            universityRecord:{
                "1":{
                    count: 0,
                    name:'嗑夜大学'
                },
                "2":{
                    count: 0,
                    name: '后现代舞蹈大学'
                },
                "3":{
                    count:0,
                    name: '新西方大学'
                },
                "4":{
                    count:0,
                    name:'真香农业大学'
                },
                "5":{
                    count:0,
                    name: '肥油大学'
                },
                "6":{
                    count:0,
                    name: '南方摸鱼大学'
                },
                "7":{
                    count:0,
                    name: '社畜研究大学'
                },
                "8":{
                    count:0,
                    name: '砖头工程大学'
                },
                "9":{
                    count:0,
                    name: '白金医护大学'
                },
                "10":{
                    count:0,
                    name: '奶思潮流大学'
                },
                "11":{
                    count:0,
                    name: '五汉子大学'
                },
                "12":{
                    count:0,
                    name: '养生医科大学'
                },
                "13":{
                    count:0,
                    name: '皇家语言大学'
                },
                "14":{
                    count:0,
                    name: '绝地农业大学'
                },
                "15":{
                    count:0,
                    name: '摸仙师范大学'
                },
                "16":{
                    count:0,
                    name: '亚洲电竞大学'
                }
            },
            answerChance: 0,
            swiperOptionA:{
                autoHeight: true,
                slidesPerView :'auto',
                spaceBetween: 10
            },
            swiperOptionB:{
                navigation: {
                    prevEl:'.prev_btn',
                    nextEl:'.next_btn'
                }   
            },
            errorTip: '验证码错误',
            sErrorTip: false,
            colorArr: 
                {
                    1:{
                      color: '#f9f1ef'
                    },
                    2:{
                      color: '#fff6e8'
                    },
                    3:{
                      color: '#ffefe8'
                    },
                    4:{
                      color: '#fff6e8'
                    },
                    5:{
                      color: '#ffefe8'
                    },
                    6:{
                      color: '#e9f7ff'
                    },
                    7:{
                      color: '#e8fdff'
                    },
                    8:{
                      color: '#e8fdff'
                    },
                    9:{
                      color: '#e9f7ff'
                    },
                    10:{
                      color: '#e9f7ff'
                    },
                    11:{
                      color: '#e9f7ff'
                    },
                    12:{
                      color: '#e9f7ff'
                    },
                    13:{
                      color: '#fff6e8'
                    },
                    14:{
                      color: '#e8fdff'
                    },
                    15:{
                      color: '#fff6e8'
                    },
                    16:{
                      color: '#fff6e8'
                    }
                  }

        },

        computed: {
            sendCodeTxt:function(){
                return `已发送(${this.sendTime})`;
            },
            currentQuestion: function(){
                return this.questionList[this.questionIndex];
            },
            prizeCount: function(){
                var _this = this;
                var index = 0;
                for(var key in _this.prizeRecord){
                    if(_this.prizeRecord.hasOwnProperty(key)){
                        if(!_this.prizeRecord[key].count){
                           index++;
                        }
                    }
                }
                return index==Object.size(_this.prizeRecord) ? 0 : 1;
            },
            universityCount: function(){
                var _this = this;
                var index = 0;
                for(var key in _this.universityRecord){
                    if(_this.universityRecord.hasOwnProperty(key)){
                        if(!_this.universityRecord[key].count){
                            index++;
                         }
                    }
                }
                return index==Object.size(_this.universityRecord) ? 0 : 1;
            },
            isPrize: function(){
                return this.prizeRecord['4'].count > 0 ? 1 : 0;
            },
            dataComplete: function(){
                var _this = this;
                return (_this.mobileCode.length == 6 && _this.mobile.length == 11 ) ? 1 : 0;
            },
            mobileComplete: function(){
                var _this = this;
                return (_this.mobile.length == 11 && !_this.sendCodeed) ? 1 : 0;
            }
        },
        destroyed: function(){
           var _this = this;
        },
        created: function(){
            var _this = this;
            _this.valideLogined();
            _this.myProfile().then(res=>{
             }).catch(err=>{
             });
            _this.getUsers();
        },
        mounted: function(){
            var _this = this;
            nie.config.stats.url.add("32723/index_0718.html?click=ymfwl","页面访问量");
            _this.getUsers();
           setTimeout(function(){
               _this.isHome = true;
           },3500);
        },
        methods:{
            getBackground:function(name){
              var uri =   __CDNPATH + '/' + name;
              return {
                  'background-size':'100% 100%',
                   'background-image': 'url('+ uri+ ')',
                  'background-repeat':  'no-repeat'
              }
            },
            getBgColor: function(index){
                var _this = this;
                
               // console.log(index);
                return {
                    'background-color': index ? _this.colorArr[index].color :''
                };
            },
            fdStatis: function(){
                if(_this.score == 7){
                    clickStats.k();
                }else{
                    clickStats.l();
                }
            },
            imgPress:function(){
                var _this = this;
                _this.imgTimer = setTimeout(function(){
                  //  console.log('img save');
                    nie.config.stats.url.add("32723/index_0718.html?click=cgbcrs","成功保存人数");
                    API.fn.share(_this.loginId).done(res=>{
                     // console.log(res);
                      if(res.success){
                        nie.config.stats.url.add("32723/index_0718.html?click=cgfxrs","成功分享人数");
                        alert('赶快去朋友圈分享吧!');
                        _this.answerChance ++;
                      }
                      //alert(res.msg);    
                       //console.log(res);
                   },1300);
                });
            },
            imgEnd: function(){
                var _this = this;
                clearTimeout(_this.imgTimer);
            },
            handleFocus: function(e){
                clearTimeout(this.inpuTimer);
            },
            handleBlur: function(){
                this.inpuTimer = setTimeout(() => {
                    window.scrollTo(0, 0);
                }, 100);
            },
            getUsers:function(){
                var _this = this;
          
                //  _this.valideLogined();
                  //_this.shareDt();
                  API.fn.finishUsers().done(res=>{
                      if(res.success){
                          var actualUser = res['finish_count'];
                          _this.finishUsers = res['finish_count'];
                          //parseInt(res['finish_count'] *10 + 5*Math.sin(res['finish_count']));
                          if(0<= actualUser && actualUser <= 1000){
                              _this.gfTxt = '第 1-1000 名满分者，可额外获得 30 天时长卡';
                          }else if(actualUser >=1001 && actualUser <= 5000){
                              _this.gfTxt = '第 1001-5000 名满分者，可额外获得 15 天时长卡';
                          }else if(actualUser>=5001 && actualUser <=15000){
                              _this.gfTxt = '第 5001-15000 名满分者，可额外获得 7 天时长卡';
                          }else{
                              _this.gfTxt = '';
                          }
                      }
                 });
            },
            showErTip: function(){
                var _this = this
                _this.sErrorTip = true;
                setTimeout(()=>{
                    _this.sErrorTip = false;
                },2000);
            },
            fxfdEvent: function(){
                var _this = this;
                window.location.replace(`./resurrect.html?university=${_this.university}&&login_id=${_this.loginId}`);
            },
            showLight: function(event){
                var _this = this;
                var index = $(event.target).parent().index()
                _this.sPopLqtz = false;
                _this.sLightPop = true;
           
                _this.$refs.swiperLight.swiper.slideTo(index );
            },
            fdpdRw: function(){
                var _this = this;
                _this.sPopFdpd = false
                _this.valChance = true;
                _this.sPopFdjh = true;
            },
            continueAnswer:function(){
                var _this = this;
                _this.valChance = true;
                clickStats.f();
                _this.getQuestions();
            },
            cancelAnswer: function(){
                var _this = this;
                clickStats.g();
                _this.valChance = true;
                _this.closePop('sPopFdpd');
            },
            closeFdpd: function(){
                var _this = this;
                _this.valChance = true;
                _this.sPopFdpd = false;
                _this.sPop = false;
            },
            imgUri: function(name){
                return __CDNPATH + '/' + name;
            },
            showHome: function(){
                var _this = this;
                _this.isHome = true;

                /*
                console.log('绘制图片开始...');
               // $('.ind5_box').css({'display':'block'});
                setTimeout(function(){
                html2canvas($(".home")[0], {
                        allowTaint:false,
                    canvas: myCanvas,
                    useCORS: true
                }).then(function(canvas) {
                    console.log('第一次绘制好了...');
                    setTimeout(function(){
                        drawHb( canvas );
                    }, 100);
                });
                }, 1000);
                */
            },
            shareDt: function(){
                var _this = this;
                API.fn.share(_this.loginId).done(res=>{
                    
                   //alert(res.msg);
                    //console.log(res);
                });
            },
            showMjl: function(){
                var _this = this;
                clickStats.a();
                _this.sPopDtjs = false;
                _this.sPopProfile = true;
            },
            showPop: function(name){
                if(name == 'sPopProfile'){
                    clickStats.a();
                }else if(name == 'sPopFdjh'){
                    clickStats.b();
                }else if (name == 'sPopLqtz'){
                    clickStats.c();
                }else if (name == 'sPopHdgz'){
                    clickStats.d();
                }
                var _this = this;
                _this.sPop = true;
                _this[name] = true;
            },
            closePop: function(name){
                var _this = this;
                _this[name] = false;
                _this.sPop = false;
            },
            showPopJlsm1: function(){
                var _this = this;
                clickStats.e();
                _this.sPop = true;
                _this.sPopJlsm = true;
            },
            showPopJlsm2: function(){
                var _this = this;
                clickStats.e();
                _this.sPopHdgz = false;
                _this.sPopJlsm = true;
            },
            showPopJlsm3:function(){
                var _this = this;
                clickStats.e();
                _this.sPopProfile = false;
                _this.sPopJlsm = true;
            },
            valideLogined: function(){
                var _this = this;
                if(_this.getCookie('login_id') && _this.getCookie('login_token') && _this.getCookie('mobile_numer')){
                    _this.logined = true;
                    _this.mobile = _this.getCookie('mobile_numer');
                    _this.loginId = _this.getCookie('login_id');
                    _this.loginToken = _this.getCookie('login_token');
                   //_this.myProfile();
                }
            },
            myProfile: function(){
                var _this = this;
                return new Promise((resolve,rej)=>{
                    API.fn.profile(_this.loginId,_this.loginToken).done(res=>{
                       // console.log(res);
                        if(res.success){
                         //   
                            var arr = res['prize_records'];
                            var univer = res['university_records'];
                            _this.answerChance = res['answer_chance'];
                            
                            arr.forEach(item=>{
                                if(item['prize_type']){
                                    _this.prizeRecord[`${item['prize_type']}`].count++;
                                }
                            })
                            //univer = [{university:1},{university:2},{university:3},{university:4},{university:6}]
                          //  console.log(univer);
                            univer.forEach(item=>{
                                if(item.university){
                                    _this.universityRecord[item.university].count++;
                                }
                            })
                            resolve(res);
                        }else{
                            _this.resetUser();
                            rej(res);
                            
                        }
                    })
                })
            },
            questionTap: function(e){
                var _this = this;
                if($(e.target).hasClass('question-item')){
                    $(e.target).addClass('active').siblings().removeClass('active');
                }else{
                    $(e.target).parent().addClass('active').siblings().removeClass('active');    
                }
                var val = _this.getQuestion() || '';
                var index = _this.questionIndex + 1; 
               // console.log(index,val);
                API.fn.submitAnswer(_this.loginId,_this.loginToken,index,val);
                
            },
            nextQuestion: function(){
                var _this = this;
                var select = _this.getQuestion() || '';
                _this.answerList.push(select);
                $('.question-item').removeClass('active');
                clearInterval(_this.dtTimer);
                console.log(_this.questionIndex);
                if(_this.questionIndex == (_this.questionList.length - 1)){
                    _this.countDown = 0;
                }else{
                    _this.countDown = 10;
                }
                
                if(_this.questionIndex <  (_this.questionList.length - 1 )){
                   
                    _this.questionIndex++;

                    if(_this.questionIndex == _this.questionList.length-1){
                        _this.nextText = "提交";
                    }

                    _this.dtTimer = setInterval(function(){
                        _this.countDown--;
                        
                        if(!_this.countDown){
                            _this.nextQuestion();
                        }
                    },1000)
                } else{
                    var answers = _this.answerList.join('-');
                    console.log(answers);
                    console.log(_this.loginId,_this.loginToken);
                   API.fn.completeAnswer(_this.loginId,_this.loginToken).done(res=>{
                       // res.success = false;
                     //   res.msg="系统错误";
                       if(res.success){
                         
                        var score = res['score'];
                        clickStats.j(score);
                        if(res['rank']){
                            _this.rank = res['rank'];
                        }
                       // console.log(res);
                        _this.score = score;
                        //_this.rank =1;
                        //_this.score = 7;
                        _this.answerChance = res['answer_chance'];
                        _this.university = res['university'];
                        _this.jltxt = '';
                        var f1 = false;
                        var f2 = false;
                        var prize = res['prize_type'];
                        var sum = 0;
                        _this.universityRecord[_this.university].count++;
                        prize.forEach(item=>{
                            if(item == 7){
                                _this.jltxt = '30天时长卡';
                                _this.prizeRecord['7'].count++;
                                f1 = true;
                            }else if (item == 6){
                                _this.jltxt = '15天时长卡';
                                _this.prizeRecord['6'].count++;
                                f1 = true;
                            }else if(item == 5){
                                _this.jltxt = '7天时长卡';
                                _this.prizeRecord['5'].count++;
                                f1 = true;
                            }

                        
                            if(item == 1){
                                sum += 10;
                                _this.prizeRecord['1'].count++;
                            }
                            if(item == 2){
                                sum +=15;
                                _this.prizeRecord['2'].count++;
                            }
                            if(item == 3){
                                sum +=30;
                                _this.prizeRecord['3'].count++;
                            }
                        })
                        if(_this.score == 7){
                            _this.jltxt += '瓜瓜卡、'
                            _this.prizeRecord['4'].count++;
                            f2 = true;
                        }
                        _this.jltxt += ((!f1 && !f2) ? (sum != 0?(_this.score<=2?`季卡减${sum}元优惠券`:`价值${sum}元优惠券`):`很遗憾未能得到奖励`) :`及价值${sum}元优惠券`);
                        if(_this.score == 7 && _this.rank){
                            //您是第xx名满分者，恭喜被 [ ] 录取，特发“”、
                            _this.fxfdText = '分享炫耀';
                            if(sum==0 && !f1 && !f2){
                                //本次考试共答对 {{score}} 题，恭喜被 [ {{universityRecord[university].name}} ] 录取特发<span>“{{jltxt}}”</span>，以资鼓励
                                _this.dtresult = `您是第${_this.rank}名满分者，恭喜被 [ ${_this.universityRecord[_this.university].name} ] 录取<br><span class="regret-info">${_this.jltxt}</span>`;
                            }else{
                                _this.dtresult = `您是第${_this.rank}名满分者，恭喜被 [ ${_this.universityRecord[_this.university].name} ] 录取<br>特发<span>“${_this.jltxt}”</span>，以资鼓励`;
                            }
                        }else{
                            _this.fxfdText = '分享获复读';
                            if(sum==0 && !f1 && !f2){
                                //本次考试共答对 {{score}} 题，恭喜被 [ {{universityRecord[university].name}} ] 录取特发<span>“{{jltxt}}”</span>，以资鼓励
                                _this.dtresult = `本次考试共答对${score} 题，恭喜被 [ ${_this.universityRecord[_this.university].name} ] 录取<br><span class="regret-info">${_this.jltxt}</span>`;
                            }else{
                                _this.dtresult = `本次考试共答对${score} 题，恭喜被 [ ${_this.universityRecord[_this.university].name} ] 录取<br>特发<span>“${_this.jltxt}”</span>，以资鼓励`;
                            }                            
                        }

                        _this.sPopDt = false;
                        _this.sPopDtjs = true;
                       }else{
                           if(res.msg.includes('token')){
                            _this.resetUser();
                            _this.sPopDt = false;
                            _this.sPop = false;
                           }else{
                            alert(res.msg);
                            return ;
                           }
                           /*
                           */
                       }
                       _this.countDown = 10;
                   });
                 
                }
               
            },
            valideChance: function(){
                var _this = this;
                if(!_this.answerChance || (_this.answerChance && _this.isPrize)){
                    _this.showPop('sPopFdpd');
                    _this.valChance = false;
                }else{
                    _this.getQuestions();
                }
            },
            getQuestion: function(){
                var val = $('.question-list').find('.question-item.active').attr('val');
                return CONSTANT[val];
            },
            getQuestions: function(){
                var _this = this;
                _this.questionIndex = 0;
                _this.answerList = [];
                _this.questionList = [];
                API.fn.questions(_this.loginId,_this.loginToken).done(res=>{
                    clickStats.i();
                    if(res.success){
                        _this.nextText = "下一题";
                        if(res.data && res.data.length > 0){
                            _this.questionList = res.data; 
                            _this.sPop = true;
                            _this.sPopDt = true;
                            _this.dtTimer = setInterval(function(){
                                _this.countDown--;
                                if(!_this.countDown){
                                    _this.nextQuestion();
                                }
                            },1000)
                        }else{
                           
                        }
                    }else{
                        _this.resetUser();
                        _this.sPop = false;
                        _this.sPopDt = false;
                    }
                })
            },
            mobileLogin: function(){
                var _this = this;

                /*
                _this.profileTimer = setInterval(function(){
                    _this.myProfile().then(res=>{
                       // console.log(res);
                    }).catch(err=>{
                        console.log(err);
                    });
                    _this.getUsers();
                },1000*60);
                */
                API.fn.loginByMobile(_this.mobile,_this.mobileCode).done(res=>{
                    if(res.success){
                     //   console.log(res);
                        var myDate = new Date();
                        var hours = myDate.getHours();
                        var hours1 = 24 - hours;
                        var exdays = hours1 * 60 * 60 * 1000;
                        _this.setCookie('login_id',res['login_id'],exdays);
                        _this.setCookie('login_token',res['login_token'],exdays);
                        _this.setCookie('mobile_numer',_this.mobile,exdays);
                        _this.valideLogined();
                        _this.myProfile().then(()=>{
                            if(!_this.answerChance || (_this.answerChance && _this.isPrize)){
                              //  console.log(_this.answerChance,_this.answerChance,_this.isPrize);
                                _this.showPop('sPopFdpd');
                                _this.valChance = false;
                            }else{
                               // console.log('')
                                _this.getQuestions();
                            }
                        }).catch(err=>{
                         //   console.log(err);
                        })
                    
                        
                    }else{
                      //  console.log(res);
                        _this.errorTip = "验证码错误";
                        _this.showErTip();
                       // _this.resetUser();
                    }
                });
            },
            sendCode: function(){
                var _this = this;
                if(ca.fn.validPhone(_this.mobile)){
                    API.fn.sendCode(_this.mobile).done(res=>{
                       // console.log(res);
                        if(res.success){
                            //clearInterval(_this.profileTimer);
                            _this.sendCodeed = true;
                            _this.sendTime = 60;
                            $(_this.$refs.sendCodeBtn).addClass('prevent');
                            _this.timer = setInterval(function(){
                                _this.sendTime--;
                                if(_this.sendTime == 0){
                                    $(_this.$refs.sendCodeBtn).removeClass('prevent');
                                    _this.sendCodeed = false;
                                    clearInterval(_this.timer);
                                }
                            },1000);
                        }else{
                            //alert(res.msg);
                            _this.errorTip = res.msg;
                            _this.showErTip();
                            _this.resetUser();
                        }
                    });
                }else{
                   alert('请填写正确的手机号！');
                }
                
            },
            closeJlsm: function(){ 
                this.sPop = false;
                this.sPopJlsm = false;
            },
            setCookie: function(cname,cvalue,exdays){
                var d = new Date();
                d.setTime(d.getTime()+exdays);
                var expires = "expires=" + d.toUTCString();
                document.cookie = cname + "=" + cvalue + ";" + expires + "; path=/";
            },
            getCookie: function(cname){
                var name = cname + "=";
                var ca = document.cookie.split(';');
                for (var i = 0; i < ca.length; i++) {
                    var c = ca[i];
                    while (c.charAt(0) == ' ') c = c.substring(1);
                    if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
                }
                return "";
            },
            resetCookie: function(cname){
               this.setCookie(cname, "", -1);
            },
            resetUser: function(){
                var _this = this;
                
                _this.resetCookie('login_id');
                _this.resetCookie('login_token');
                _this.resetCookie('mobile_numer');
                _this.mobile = '';
                _this.mobileCode = '';
                _this.logined = false;
          
                _this.answerChance = 0;
                _this.questionIndex = 0;


                $(_this.$refs.sendCodeBtn).removeClass('prevent');
                _this.sendCodeed = false;
                clearInterval(_this.timer);
                
                for(var key in _this.universityRecord){
                    if(_this.universityRecord.hasOwnProperty(key)){
                        _this.universityRecord[key].count = 0;
                    }
                }
                for(var key in _this.prizeRecord){
                    if(_this.prizeRecord.hasOwnProperty(key)){
                        _this.prizeRecord[key].count = 0;
                    }
                }
             //   alert('请重新登录！');
            }
        }
    });

});


nie.define('API',function(){

    var hostObj = {
        testHost: "https://igor-test.dev.webapp.163.com:8007/",
        releaseHost: "https://uu-quest.webapp.163.com/"//http://uu-quest.webapp.163.com/
    };
    
    
    const jsonp = (url,data)=>{
        var host = hostObj.releaseHost ? hostObj.releaseHost : hostObj.testHost;
        return $.ajax({
            url: host + url,
            data: $.extend({},data),
            type: 'GET',
            dataType: 'jsonp',
            timeout: 10000,
            error () {
                alert('网络错误，请稍后再试！');
            }
        })
    }   

    return {
        fn: {
            sendCode(mobile){
                //发送验证码
                return jsonp('get_authcode',{
                    mobile
                });
            },
            loginByMobile(mobile,authcode){
                //手机号登录
                return jsonp('verify',{
                    mobile,
                    authcode
                });
            },
            profile(login_id,login_token){
                return jsonp('profile',{
                    login_id,
                    login_token
                });
            },
            questions(login_id,login_token){
                //获得题目列表
                return jsonp('questions',{
                    login_id,
                    login_token
                });
            },
            completeAnswer(login_id,login_token){
                //提交完整答案
                return jsonp('complete',{
                    login_id,
                    login_token
                })
            },
            submitAnswer(login_id,login_token,question_id,answer){
                //分次提交答案
                return jsonp('submit_answer',{
                    login_id,
                    login_token,
                    question_id,
                    answer
                });
            },
            share(login_id){
                //转发
                return jsonp('share',{
                    login_id
                });
            },
            finishUsers(){
                //获取瓜分人数
                return jsonp('finish_users');
            }
        }
    }
})
